<?php

namespace api\modules\v1\forms\clinic;

use Yii;
use yii\base\Model;
use common\models\member\Member;
use common\models\clinic\Project;
use common\models\clinic\TreatmentRoom;

/**
 * 治疗项目
 *
 * Class TreatmentRoomForm
 * @package api\modules\v1\forms\clinic
 */
class TreatmentRoomForm extends Model
{
    /**
     * 治疗室ID
     *
     * @var
     */
    public $id;

    /**
     * 治疗室名
     *
     * @var
     */
    public $name;

    /**
     * 项目ID
     *
     * @var
     */
    public $project_id;

    /**
     * 治疗室状态
     *
     * @var
     */
    public $status;

    /**
     * 图标ID
     *
     * @var
     */
    public $icon_id;

    /**
     * 治疗项目IDs
     *
     * @var
     */
    public $clinic_project_ids;

    /**
     * 治疗室信息
     *
     * @var array
     */
    protected $clinicTreatmentRoom;


    /**
     * 治疗室绑定治疗项目列表
     *
     * @var array
     */
    protected $clinicProjectBindList = null;

    /**
     * 新增治疗项目
     *
     * @var array
     */
    protected $addClinicProjectIds = [];

    /**
     * 删除治疗项目
     *
     * @var array
     */
    protected $deleteClinicProjectIds = [];


    public function rules()
    {
        return [
            // 参数验证
            [['project_id', 'name', 'status', 'icon_id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['create']],
            [['project_id', 'id', 'name', 'status', 'icon_id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit']],
            [['project_id', 'id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['delete']],
            [['project_id', 'id', 'status'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit_status']],
            [['project_id', 'id', 'clinic_project_ids'], 'required', 'message' => '{attribute}不能为空', 'on' => ['bind_project']],

            [['project_id'], 'checkProjectId', 'skipOnEmpty' => false, 'on' => ['create', 'edit', 'delete', 'edit_status', 'bind_project']],
            [['id'], 'checkClinicTreatmentRoom', 'skipOnEmpty' => false, 'on' => ['edit', 'delete', 'edit_status', 'bind_project']],
            [['name'], 'checkName', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['status'], 'checkStatus', 'skipOnEmpty' => false, 'on' => ['create', 'edit', 'edit_status']],
            [['icon_id'], 'checkIconId', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['clinic_project_ids'], 'checkClinicProjectIds', 'skipOnEmpty' => false, 'on' => ['bind_project']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        // 新增
        $scenarios['create'] = ['project_id', 'name', 'status', 'icon_id'];

        // 编辑
        $scenarios['edit'] = ['project_id', 'id', 'name', 'status', 'icon_id'];

        // 删除
        $scenarios['delete'] = ['project_id', 'id'];

        // 切换部门状态
        $scenarios['edit_status'] = ['project_id', 'id', 'status'];

        // 绑定治疗项目
        $scenarios['bind_project'] = ['project_id', 'id', 'clinic_project_ids'];

        return $scenarios;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'id' => '治疗室ID',
            'name' => '治疗室名称',
            'project_id' => '项目ID',
            'status' => '状态',
            'icon_id' => '图标ID',
            'clinic_project_ids' => '治疗项目IDs',
        ];
    }

    /**
     * 检验项目ID
     *
     * @param $attribute
     * @return bool
     */
    public function checkProjectId($attribute)
    {
        if (Yii::$app->user->identity->member->is_super == Member::IS_SUPER_YES) {
            return true;
        }

        $attr = Yii::$app->services->attr->findInfo([
            'member_id' => Yii::$app->user->identity->member_id,
            'project_id' => $this->project_id,
        ]);

        if (!$attr) {
            $this->addError($attribute, '未绑定当前项目，无法操作');
            return true;
        }
    }

    /**
     * 检验治疗室信息
     *
     * @param $attribute
     * @return bool
     */
    public function checkClinicTreatmentRoom($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $clinicTreatmentRoom = $this->getClinicTreatmentRoom();
        if (!$clinicTreatmentRoom) {
            $this->addError($attribute, '参数错误[id_error]');
            return true;
        }

        if ($clinicTreatmentRoom->status == TreatmentRoom::STATUS_DELETE) {
            $this->addError($attribute, '治疗室已删除，无法操作');
            return true;
        }

//        if (($this->getScenario() == 'edit' && $this->status == Project::STATUS_INVALID)
//            || $this->getScenario() == 'delete'
//            || ($this->getScenario() == 'edit_status' && $this->status == Project::STATUS_INVALID)
//        ) {
//            $attr = Yii::$app->services->attr->findInfo(['clinic_id' => $this->id]);
//
//            if ($attr) {
//                $this->addError($attribute, "该诊室有人员绑定，无法操作");
//                return true;
//            }
//        }
    }

    /**
     * 校验治疗室名称
     *
     * @param $attribute
     */
    public function checkName($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->name);
        if ($len > 50) {
            $this->addError($attribute, '治疗室名称过长，最多50个字');
            return true;
        }

        // 是否检验
        $isCheck = true;
        if ($this->getScenario() == 'edit') {
            $clinicTreatmentRoom = $this->getClinicTreatmentRoom();
            // 治疗室名称未变【跳过】
            if ($clinicTreatmentRoom->name == $this->name) {
                $isCheck = false;
            }
        }

        if ($isCheck) {
            $clinicTreatmentRoomInfo = Yii::$app->services->clinicTreatmentRoom->findInfo([
                'project_id' => $this->project_id,
                'name' => $this->name,
                'status' => [TreatmentRoom::STATUS_INVALID, TreatmentRoom::STATUS_ENABLE],
            ]);

            if ($clinicTreatmentRoomInfo) {
                $this->addError($attribute, "治疗室【{$this->name}】已存在");
                return true;
            }
        }
    }

    /**
     * 校验治疗室状态
     *
     * @param $attribute
     */
    public function checkStatus($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (!in_array($this->status, [TreatmentRoom::STATUS_INVALID, TreatmentRoom::STATUS_ENABLE])) {
            $this->addError($attribute, "参数错误[status_error]");
            return true;
        }
    }

    /**
     * 校验图标ID
     *
     * @param $attribute
     */
    public function checkIconId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if ($this->icon_id <=0 || $this->icon_id > 12) {
            $this->addError($attribute, "参数错误[icon_id_error]");
            return true;
        }
    }

    /**
     * 校验治疗项目IDs
     *
     * @param $attribute
     */
    public function checkClinicProjectIds($attribute)
    {
        // 治疗项目IDs
        $clinicProjectIdsArr = $this->clinic_project_ids ? array_unique(explode(',', $this->clinic_project_ids)) : [];
        $clinicProjectList = Yii::$app->services->clinicProject->findList(['id' => $clinicProjectIdsArr]);
        foreach ($clinicProjectList as $row) {
            if ($row['status'] == Project::STATUS_DELETE) {
                $this->addError($attribute, "治疗项目已删除，无法绑定");
                return true;
            }
        }

        $hasClinicProjectIds = array_column($clinicProjectList, 'id');

        // 获取治疗项目列表
        $clinicProjectBind = $this->getClinicProjectBind();
        $clinicProjectIds = array_column($clinicProjectBind, 'clinic_project_id');

        // 删除项目IDs
        $this->deleteClinicProjectIds = array_diff($clinicProjectIds, $hasClinicProjectIds);

        // 交集，存在部分
        $hasIds = array_intersect($clinicProjectIds, $hasClinicProjectIds);

        // 新增项目IDs
        $this->addClinicProjectIds = array_diff($hasClinicProjectIds, $hasIds);
    }

    /**
     * 获取治疗室信息
     *
     * @return array|TreatmentRoom|null
     */
    public function getClinicTreatmentRoom()
    {
        if (empty($this->clinicTreatmentRoom)) {
            $this->clinicTreatmentRoom = Yii::$app->services->clinicTreatmentRoom->findById($this->id);
        }

        return $this->clinicTreatmentRoom;
    }

    /**
     * 获取治疗室绑定项目
     *
     * @return array|TreatmentRoom|null
     */
    public function getClinicProjectBind()
    {
        if (is_null($this->clinicProjectBindList)) {
            $this->clinicProjectBindList = Yii::$app->services->clinicProjectBind->findList(['treatment_room_id' => $this->id]);
        }

        return $this->clinicProjectBindList;
    }

    /**
     * 获取新增治疗项目
     *
     * @return array|TreatmentRoom|null
     */
    public function getAddClinicProjectIds()
    {
        return $this->addClinicProjectIds;
    }

    /**
     * 获取删除治疗项目
     *
     * @return array|TreatmentRoom|null
     */
    public function getDeleteClinicProjectIds()
    {
        return $this->deleteClinicProjectIds;
    }
}